package
{
	
	import flash.desktop.NativeProcess;
	import flash.desktop.NativeProcessStartupInfo;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.BitmapDataChannel;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.FileReference;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	import mx.graphics.codec.JPEGEncoder;
	import mx.graphics.codec.PNGEncoder;
	
	import spark.components.Label;
	
	import MP.MapExpandVO;
	import MP.MapdataTranfromExpand;
	
	/**
	 * 地图文件.mp破解成png
	 */
	public class MP_Decode
	{
		private static var _ins:MP_Decode;
		
		public static var exportUrl:String;
		public static var importRoot:String;
		public static var printMsg:Label;
		
		public static var dataDic:Object = {};
		
		private var _cfgStream:FileStream;
		private var _urlLoader:URLLoader;
		
		public var resType:int = 2;
		private var _path:String;
		private var _dataPath:String;
		private var _rootPath:String;
		private var _outPath:String;
		private var _mapData:MapExpandVO;
		
		private var _subDirec:String;
		
		private var _timer:Timer;
		private var _timer2:Timer;
		
		public static function get ins():MP_Decode
		{
			if(!_ins){
				_ins = new MP_Decode();
			}
			return _ins;
		}
		
		public function MP_Decode()
		{
		}
		public function doLoad(path:String):void
		{
			//"C:\Users\Administrator\Desktop\ani原始\21000\bg_tiles\1.mp"
			
			_path = path;
//			var path:String = "29.mp";
			
			var index:int = path.indexOf("bg_tiles");
			_subDirec = "bg_tiles";
			if(index == -1){
				index = path.indexOf("tiles");
				_subDirec = "tiles";
			}
			if(index != -1){
				_rootPath = path.substring(0, index);
				
				_dataPath = _rootPath + "data_zip.mp";
			}
			
			loadData();
		}
		/**
		 * 如果有地图数据，则加载
		 */
		private function loadData():void
		{
			if(_dataPath){
				if(dataDic[_dataPath]){
					_mapData = dataDic[_dataPath];
					loadClip();
					return;
				}
				var request:URLRequest = new URLRequest(_dataPath);
				_urlLoader = new URLLoader();
				_urlLoader.addEventListener(Event.COMPLETE, onComplete1);
				_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoadError1);
				_urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onLoadError2);
				_urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoadError2);
				_urlLoader.data = null;
				_urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
				_urlLoader.load(request);
			}
			else{
				loadClip();
			}
		}
		private function onComplete1(e:Event):void
		{
			_urlLoader.removeEventListener(Event.COMPLETE, onComplete1);
			_urlLoader.removeEventListener(IOErrorEvent.IO_ERROR, onLoadError1);
			_urlLoader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, onLoadError2);
			_urlLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoadError2);
			
			
			var bytes:ByteArray = decodeBytes(_urlLoader.data);
			bytes.position = 0;
			
			if(!dataDic[_dataPath]){
				dataDic[_dataPath] = new MapdataTranfromExpand().tranfromToMapVO(bytes) as MapExpandVO;
			}
			_mapData = dataDic[_dataPath];
			
			loadClip();
		}
		private function onLoadError1(e:Event):void
		{
			trace("加载是失败");
			loadClip();
		}
		private function onLoadError2(e:Event):void
		{
			trace("加载是失败2");
		}
		private function decodeBytes(bytes:ByteArray):ByteArray {
			
			
			bytes.position = 0;
			//			var strleng:int = bytes.readInt();
			//			var version:String = bytes.readMultiByte(strleng, "utf-8");
			var binary:ByteArray = new ByteArray();
			bytes.readBytes(binary);
			binary.uncompress();
			return binary;
		}
		
		/**
		 * 开始加载切片
		 */
		private function loadClip():void
		{
			var request:URLRequest = new URLRequest(_path);
			_urlLoader = new URLLoader();
			_urlLoader.addEventListener(ProgressEvent.PROGRESS, onProgress);
			_urlLoader.addEventListener(Event.COMPLETE, onComplete);
			_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
			_urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
			_urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoadError);
			_urlLoader.addEventListener(Event.OPEN, onLoadOpen);
			_urlLoader.data = null;
			_urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
			_urlLoader.load(request);
		}
		private function onProgress(e:Event):void
		{
			
		}
		private function onComplete(e:Event):void
		{
			loadBytes(_urlLoader.data as ByteArray);
		}
		private function onLoadError(e:Event):void
		{
			
		}
		private function onStatus(e:Event):void
		{
			
		}
		private function onLoadOpen(e:Event):void
		{
			
		}
		
		
		//------------------------------------------------------------
		
		public function loadBytes(bytes:ByteArray, context:LoaderContext=null):void
		{
			bytes.uncompress();
			
			var loadContext:LoaderContext = context;
			if (loadContext == null)
			{
				loadContext = new LoaderContext(false, new ApplicationDomain(ApplicationDomain.currentDomain));
			};
			var l:Loader = new Loader();
			
			l.contentLoaderInfo.addEventListener(Event.COMPLETE, this.onComplete2);
			l.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onSecurityError);
			l.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.onIoError);
			try
			{
				l.loadBytes(bytes, loadContext);
			} catch(e:ArgumentError)
			{
				onIoError(null);
			};
		}
		protected function onComplete2(e:Event):void
		{
			resType = 1;
			
			var isMask:Boolean = false;
			if(_mapData){
				var index:int = _path.lastIndexOf("\\");
				var char:String = _path.substring(index + 1, _path.indexOf(".mp"));
				var id:int = parseInt(char);
				if (_mapData.hasBottomMap)
				{
					if (_mapData.clipsData){
						isMask = _mapData.clipsData[id - 1] == 1? false:true;
					}
					else{
						isMask = true;
					}
					
					if(_subDirec == "tiles"){
						resType = 2;//输出png
					}
				}
			}
			
			var data:Bitmap = ((e.target as LoaderInfo).content as Bitmap);
			var scrBmd:BitmapData = data.bitmapData;
			
			if(!isMask){
				writeImg(scrBmd, _path);
				return;
			}
			
			var time:int = getTimer();
			var bmd:BitmapData = new BitmapData(scrBmd.width, scrBmd.height / 2);
			//复制图片的真实像素区域 
			var p:Point = new Point();
			var rect:Rectangle = new Rectangle(0, 0, bmd.width, bmd.height);
			bmd.copyPixels(scrBmd, rect, p);
			rect.y = bmd.height;
			//复制图片的下半区域的红色通道到新图的alpha通道里来实现透明
			bmd.copyChannel(scrBmd, rect, p, BitmapDataChannel.RED, BitmapDataChannel.ALPHA);
			//scrBmd.dispose();
//			logInfo("转换[" + scrBmd.width + "*" + scrBmd.height + "]消耗:" + (getTimer() - time)+" ms");
			
//			var bmp:Bitmap = new Bitmap();
			
			writeImg(bmd, _path);
		}
		
		protected function onSecurityError(e:SecurityErrorEvent):void
		{
			
		}
		protected function onIoError(e:IOErrorEvent):void
		{
			
		}
		
		//------------output=------------------------
		public function writeImg(param1:BitmapData, path:String):void
		{
			var path:String = _path.replace(importRoot, "");
			if(path.indexOf("\\") == 0){
				path = path.substring(1);
			}
			
			var imgByteArray:ByteArray;
			var jpgenc:JPEGEncoder;
			var pngenc:PNGEncoder;
			var msg:Label;
			var bmd:BitmapData = param1;
			var laststr:String;
			if(resType == 1)//从json拆分
			{
				jpgenc = new JPEGEncoder(80);
				imgByteArray = jpgenc.encode(bmd);
			 	path = path.replace(".mp", ".jpg");
				
//				imgByteArray.compress();
			}
			else
			{
				pngenc = new PNGEncoder();
				imgByteArray = pngenc.encode(bmd);
				path = path.replace(".mp", ".png");
			}
			_outPath = path;
			
			var rootFile:File = new File(exportUrl);
			var fl:File = rootFile.resolvePath(path);
			var fs:FileStream = new FileStream();
			
			try
			{
				fs.open(fl, FileMode.WRITE);
				fs.writeBytes(imgByteArray);
				fs.close();
				
				if(resType != 1){
					if(!_timer){
						_timer = new Timer(100);
						_timer.addEventListener(TimerEvent.TIMER, onTimer);
						_timer.start();
					}
				}
			}
			catch(e:Error)
			{
				throw new Error("打包出错：" + path);
			}
		}
		private function onTimer(e:TimerEvent):void
		{
			var rootFile:File = new File(exportUrl);
			var fl:File = rootFile.resolvePath(_outPath);
			if(fl.exists){
				_timer.removeEventListener(TimerEvent.TIMER, onTimer);
				_timer.stop();
				
				var f:File = new File("d:/pngquant/pngquant.exe");// File.applicationDirectory;
				f = f.resolvePath("d:/pngquant/pngquant.exe");
				var na:NativeProcessStartupInfo = new NativeProcessStartupInfo();//AIR2.0中的新类, 创建进程的信息对象
				na.executable = f;// 将你指定的MyFile对象指定为可执行文件
				var arr:Vector.<String> = new Vector.<String>();
//				arr.push("D:/pngquant/2010_tx10.ani.png");
				
				var path:String = fl.nativePath.replace(/\\/gi, "\/");
				arr.push(path);
				na.arguments = arr;
				var process:NativeProcess = new NativeProcess;// 创建一个本地进程
				process.start(na);// 运行本地进程
				
				_timer.addEventListener(TimerEvent.TIMER, onTimer2);
				_timer.start();
			}
		}
		private function onTimer2(e:TimerEvent):void
		{
			var fix:String = _outPath.substring(_outPath.lastIndexOf("."));
			var path:String = _outPath.replace(fix, "-fs8" + fix);
			
			var rootFile:File = new File(exportUrl);
			var fl:File = rootFile.resolvePath(path);
			if(fl.exists){
				
				_timer.removeEventListener(TimerEvent.TIMER, onTimer2);
				_timer.stop();
				_timer = null;
				
				var rootFile:File = new File(exportUrl);
				var fl2:File = rootFile.resolvePath(_outPath);
				
				fl.moveTo(fl2, true);
			}
		}
		
		
		private static var testNum:int = 1;
		/**
		 * 调用外部程序
		 */
		public static function callExe():void
		{
			try{
				
				var f:File = new File("d:/pngquant/pngquant.exe");// File.applicationDirectory;
				f = f.resolvePath("d:/pngquant/pngquant.exe");
				var na:NativeProcessStartupInfo = new NativeProcessStartupInfo();//AIR2.0中的新类, 创建进程的信息对象
				na.executable = f;// 将你指定的MyFile对象指定为可执行文件
				var arr:Vector.<String> = new Vector.<String>();
//				arr.push("D:/pngquant/2010_tx10.ani.png");
//				arr.push("C:/Users/Administrator/Desktop/ani输出/21000/tiles/"+(testNum++)+".png");
//				arr.push("D:/pngquant/中文/"+(testNum++)+".png");
//				arr.push("D:/pngquant/english/"+(testNum++)+".png");
//				arr.push("C:/Users/Administrator/Desktop/ani-out/cb002/14_0_1.png");
				arr.push("D:/pngquant/14_0_1.png");
//				arr.push("C:\Users\Administrator\Desktop\ani输出\21000\tiles\1.png");
//				arr.push("C:\Users\Administrator\Desktop\ani输出\21000\tiles\1.png");
				na.arguments = arr;
				var process:NativeProcess = new NativeProcess();// 创建一个本地进程
				Png2Jpg.printMsg.text = "设备是否支持：" + NativeProcess.isSupported;
				
				process.start(na);// 运行本地进程
				
				//				throw new Error("蓝色的多少");
			}
			catch(e:*){
				Png2Jpg.printMsg.text = "报错了！！！";
				trace("这是什么错？");
			}
		}
		
	}
}